<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>数据列表</span>
        <el-button type="primary" :icon="Plus" @click="openUploadDrawer">
          上传数据
        </el-button>
      </div>
    </template>

    <!-- 查询表单 -->
    <el-form inline :model="queryForm" class="query-form" style="margin-bottom: 20px;">
      <el-form-item label="数据源类型">
        <el-select v-model="queryForm.type" placeholder="请选择数据源类型">
          <el-option label="无人机" value="drone"></el-option>
          <el-option label="卫星" value="satellite"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="区域">
        <el-select
            v-model="queryForm.area"
            placeholder="请选择区域"
            :disabled="queryForm.type === '卫星'"
        >
          <el-option label="哈达湾" value="hadawan"></el-option>
          <el-option label="鸟岛" value="niaodao"></el-option>
          <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
          <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
          <el-option label="泉湾" value="quanwan"></el-option>
          <el-option label="黑马河口" value="heimahekou"></el-option>
          <el-option label="沙柳河口" value="shaliuhekou"></el-option>
          <el-option label="泉吉河口" value="quanjihekou"></el-option>
          <el-option label="二郎剑" value="erlangjian"></el-option>
          <el-option label="一郎剑子湖" value="yilangjianzihu"></el-option>
          <el-option label="洱海" value="erhai"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="dataList"
        border
        style="width: 100%; margin-bottom: 20px"
    >
      <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="type"
          label="数据源类型"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="area"
          label="区域"
          align="center"
      ></el-table-column>

      <el-table-column
          prop="algalBloomArea"
          label="藻华面积(公顷)"
          width="140"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="date"
          label="数据采集时间"
          width="160"
          align="center"
      ></el-table-column>
      <el-table-column
          label="操作"
          width="250"
          align="center"
      >
        <template #default="scope">
          <el-button :icon="View" circle plain type="primary" @click="handleViewMore(scope.row)"></el-button>
          <el-button :icon="Edit" circle plain type="success" @click="handleEdit(scope.row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>

    <!-- 详情抽屉 -->
    <el-drawer
        v-model="detailDrawer"
        title="数据详情"
        direction="rtl"
        size="50%"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="数据源类型">{{ currentData.type }}</el-descriptions-item>
        <el-descriptions-item label="区域">{{ currentData.area }}</el-descriptions-item>
        <el-descriptions-item label="藻华面积(公顷)">{{ currentData.algalBloomArea }}</el-descriptions-item>
        <el-descriptions-item label="数据采集时间">{{ currentData.date }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 上传数据抽屉 -->
    <el-drawer
        v-model="uploadDrawer"
        title="上传数据"
        direction="rtl"
        size="50%"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          size="large"
      >
        <!-- 数据源类型 -->
        <el-form-item label="数据源类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择数据源类型">
            <el-option label="无人机" value="drone"></el-option>
            <el-option label="卫星" value="satellite"></el-option>
          </el-select>
        </el-form-item>

        <!-- 区域 -->
        <el-form-item label="区域" prop="area">
          <el-select v-model="formData.area" placeholder="请选择区域">
            <el-option label="哈达湾" value="hadawan"></el-option>
            <el-option label="鸟岛" value="niaodao"></el-option>
            <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
            <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
            <el-option label="泉湾" value="quanwan"></el-option>
            <el-option label="黑马河口" value="heimahekou"></el-option>
            <el-option label="沙柳河口" value="shaliuhekou"></el-option>
            <el-option label="泉吉河口" value="quanjihekou"></el-option>
            <el-option label="二郎剑" value="erlangjian"></el-option>
            <el-option label="一郎剑子湖" value="yilangjianzihu"></el-option>
            <el-option label="洱海" value="erhai"></el-option>
          </el-select>
        </el-form-item>

        <!-- 藻华面积 -->
        <el-form-item label="藻华面积(公顷)" prop="algalBloomArea">
          <el-input v-model="formData.algalBloomArea" placeholder="请输入藻华面积"
                    type="text"></el-input>
        </el-form-item>

        <!-- 数据采集时间 -->
        <el-form-item label="数据采集时间" prop="date">
          <el-date-picker
              v-model="formData.date"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择数据采集时间"
              :prefix-icon="Calendar"
          ></el-date-picker>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" size="large" @click="handleSubmit">
            上传数据
          </el-button>
          <el-button size="large" @click="handleCloseUploadDrawer" style="margin-left: 10px">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 编辑数据抽屉 -->
    <el-drawer
        v-model="editDrawer"
        title="编辑数据"
        direction="rtl"
        size="50%"
    >
      <el-form
          ref="editFormRef"
          :model="editFormData"
          :rules="rules"
          label-width="120px"
          size="large"
      >
        <el-form-item label="ID" prop="id">
          <el-input v-model="editFormData.id" disabled></el-input>
        </el-form-item>

        <!-- 数据源类型 -->
        <el-form-item label="数据源类型" prop="type">
          <el-select v-model="editFormData.type" placeholder="请选择数据源类型">
            <el-option label="无人机" value="drone"></el-option>
            <el-option label="卫星" value="satellite"></el-option>
          </el-select>
        </el-form-item>

        <!-- 区域 -->
        <el-form-item label="区域" prop="area">
          <el-select v-model="editFormData.area" placeholder="请选择区域">
            <el-option label="哈达湾" value="hadawan"></el-option>
            <el-option label="鸟岛" value="niaodao"></el-option>
            <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
            <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
            <el-option label="泉湾" value="quanwan"></el-option>
            <el-option label="黑马河口" value="heimahekou"></el-option>
            <el-option label="沙柳河口" value="shaliuhekou"></el-option>
            <el-option label="泉吉河口" value="quanjihekou"></el-option>
            <el-option label="二郎剑" value="erlangjian"></el-option>
            <el-option label="一郎剑子湖" value="yilangjianzihu"></el-option>
            <el-option label="洱海" value="erhai"></el-option>
          </el-select>
        </el-form-item>

        <!-- 藻华面积 -->
        <el-form-item label="藻华面积(公顷)" prop="algalBloomArea">
          <el-input v-model="editFormData.algalBloomArea" placeholder="请输入藻华面积"></el-input>
        </el-form-item>

        <!-- 数据采集时间 -->
        <el-form-item label="数据采集时间" prop="date">
          <el-date-picker
              v-model="editFormData.date"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择数据采集时间"
              :prefix-icon="Calendar"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleUpdate">保存</el-button>
          <el-button @click="editDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Plus, View, Delete, Calendar, Edit } from '@element-plus/icons-vue'
import { dataListService, dataSaveService, dataDeleteService, dataUpdateService } from '@/api/data'
import request from "@/utils/request";
import {ElMessage, ElMessageBox} from 'element-plus'

// 数据列表
const dataList = ref([])
// 加载状态
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 详情抽屉
const detailDrawer = ref(false)
const currentData = ref({})

// 上传抽屉
const uploadDrawer = ref(false)
const formRef = ref(null)

// 编辑抽屉相关
const editDrawer = ref(false)
const editFormRef = ref(null)
const editFormData = reactive({
  id: '',
  type: '',
  area: '',
  algalBloomArea: '',
  date: ''
})

// 表单数据
const formData = ref({
  type: '',
  area: '',
  algalBloomArea: '',
  date: ''
})

// 区域映射表 - 将汉字映射为拼音
const areaMap = {
  '哈达湾': 'hadawan',
  '鸟岛': 'niaodao',
  '布哈河口海北区': 'buhahekouhaibeiqu',
  '布哈河口海南区': 'buhahekouhainanqu',
  '泉湾': 'quanwan',
  '黑马河口': 'heimahekou',
  '沙柳河口': 'shaliuhekou',
  '泉吉河口': 'quanjihekou',
  '二郎剑': 'erlangjian',
  '一郎剑子湖': 'yilangjianzihu',
  '洱海': 'erhai'
}

// 表单验证规则
const rules = {
  type: [
    { required: true, message: '请选择数据源类型', trigger: 'change' }
  ],
  area: [
    { required: true, message: '请选择区域', trigger: 'change' }
  ],
  algalBloomArea: [
    { required: true, message: '请输入藻华面积', trigger: 'blur' },
  ],
  date: [
    { required: true, message: '请选择数据采集时间', trigger: 'change' }
  ]
}

// 查询表单数据
const queryForm = ref({
  type: '',
  area: '',
})

// 获取数据列表
const getDataList = async (isQuery = false) => {
  try {
    loading.value = true
    let result
    if (isQuery) {
      result = await request.post('/data/query', {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...queryForm.value
      })
    } else {
      result = await dataListService({
        pageNum: currentPage.value,
        pageSize: pageSize.value
      })
    }
    dataList.value = result.data.items
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  getDataList()
})

// 分页事件处理
const handlePageChange = (page) => {
  currentPage.value = page
  const isQuery = Object.values(queryForm.value).some(val => val !== '')
  getDataList(isQuery)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  const isQuery = Object.values(queryForm.value).some(val => val !== '')
  getDataList(isQuery)
}

// 查看更多详情
const handleViewMore = (row) => {
  currentData.value = { ...row }
  detailDrawer.value = true
}

// 编辑数据
const handleEdit = (row) => {
  editDrawer.value = true
  // 复制行数据到编辑表单，并将区域汉字转换为拼音
  Object.assign(editFormData, {
    ...row,
    area: areaMap[row.area] || row.area // 将汉字区域转换为拼音
  })
}

// 更新数据
const handleUpdate = async () => {
  try {
    await editFormRef.value.validate()
    await dataUpdateService(editFormData)
    ElMessage.success('更新成功')
    editDrawer.value = false
    getDataList()
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('更新失败：' + (error.message || '未知错误'))
    }
  }
}

// 打开上传抽屉
const openUploadDrawer = () => {
  uploadDrawer.value = true
  formRef.value?.resetFields()
  formData.value = {
    type: '',
    area: '',
    algalBloomArea: '',
    date: ''
  }
}

// 提交上传数据
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    await dataSaveService(formData.value)
    ElMessage.success('数据上传成功')
    uploadDrawer.value = false
    getDataList()
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('数据上传失败：' + (error.message || '未知错误'))
    }
  }
}

// 关闭上传抽屉
const handleCloseUploadDrawer = () => {
  uploadDrawer.value = false
}

// 删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定要删除这条数据吗？',
      '确认删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await dataDeleteService(row.id)
      ElMessage.success('删除成功')
      getDataList()
    } catch (error) {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  })
}

// 处理查询
const handleQuery = () => {
  currentPage.value = 1
  getDataList(true)
}

// 重置查询条件
const resetQuery = () => {
  queryForm.value = {
    type: '',
    area: ''
  }
  currentPage.value = 1
  getDataList()
}
</script>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.query-form {
  padding: 10px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding-left: 16px;
}
</style>